﻿using CCWin;
using COMMON.Http;
using COMMON.Http.Sender;
using COMMON.Json;
using 易保全;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace 易保全
{
    /// <summary>
    /// 登录窗体
    /// </summary>
    public partial class LoginForm : CCSkinMain
    {
        public LoginForm()
        {
            InitializeComponent();
            //Todo移除默认账号信息
            if (File.Exists(System.Windows.Forms.Application.StartupPath + "/ebq.dl_"))
            {
                string userInfo = File.ReadAllText(System.Windows.Forms.Application.StartupPath + "/ebq.dl_");
                string[] infos = userInfo.Split('\n');
                this.tbAccount.Text = infos[0];
                this.tbPwd.Text = infos[1];
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
        private bool postlogin()
        {
            if (AppInfo.remenberPwd)
            { //如果点击了记住密码 那么将用户信息写到本地
                File.WriteAllText(System.Windows.Forms.Application.StartupPath + "/ebq.dl_", this.tbAccount.Text.Trim() + "\n" + this.tbPwd.Text.Trim());
            }
            else {//用户不保存密码的时候删除密码文件
                if (File.Exists(System.Windows.Forms.Application.StartupPath + "/ebq.dl_"))
                {
                    File.Delete(System.Windows.Forms.Application.StartupPath + "/ebq.dl_");
                }
            }
            Dictionary<string, object> dict = new Dictionary<string, object>();
            dict.Add(AppInfo.LoginAccountKey, this.tbAccount.Text.Trim());
            dict.Add(AppInfo.LoginPwdKey, this.tbPwd.Text.Trim());

            PostSender sender1 = new PostSender(AppInfo.LoginUrl, dict, new Dictionary<string, object>());
            HttpWebResponse resp = null;
            try
            {
                resp = sender1.send(AppInfo.Delay, null, null);
            }
            catch
            {
                new FrmMsg("系统提示", "登录超时,请检查你的网络状况").ShowDialog();
                changeView(true);
                return false;
            }
            string json = ResponseHelper.GetResponseString(resp);
            Dictionary<string, object> o = null;
            try
            {
                o = JSONResponseParser.parse(json) as Dictionary<string, object>;
            }
            catch
            {
                new FrmMsg("系统提示", "服务器暂停服务！").ShowDialog();
                changeView(true);
                return false;
            }
            object statusValue = false;

            bool flag = o.TryGetValue("success", out statusValue);
            if (flag && (bool.Parse(statusValue.ToString())))
            {
                //持有header
                AppInfo.Cookies = resp.Headers["Set-Cookie"];
                //登录成功
                doSetAppInfo(o);
                this.DialogResult = DialogResult.OK;
                this.Close();
                return true;
            }
            else
            {
                new FrmMsg("系统提示", "登录失败！").ShowDialog();
                changeView(true);
                return false;
            }
        }
        private void doSetAppInfo(Dictionary<string, object> o)
        {
            Dictionary<string, object> oData = getDictValue("result", o) as Dictionary<string, object>;
            AppInfo.ImagePath = getDictValue("imagePath", oData) as string;

            object obj_userId = getDictValue("userId", oData);
            AppInfo.LoginStatus = true;
            AppInfo.UserId = obj_userId.ToString();
            AppInfo.UserName = getDictValue("username", oData) as string;
            AppInfo.AuthStatus = getDictValue("status", oData) as string;
            AppInfo.SessionId = getDictValue("jSESSIONID", oData) as string;
        }

        private object getDictValue(string key, Dictionary<string, object> dict)
        {
            object ret = null;
            bool flag = dict.TryGetValue(key, out ret);
            return ret;
        }
        private void FrmLogin_Load(object sender, EventArgs e)
        {
            btnLogin.Click += new EventHandler(DelegateLogin);
            tbPwd.KeyUp += new KeyEventHandler(DelegateLogin);
            tbAccount.KeyUp += new KeyEventHandler(DelegateLogin);
        }

        private void changeView(bool flag) {
            label1.Visible = flag;
            tbAccount.Visible = flag;
            label2.Visible = flag;
            tbPwd.Visible = flag;
            pictureBox2.Visible = flag;
            button3.Visible = flag;
            button2.Visible = flag;
            btnLogin.Visible = flag;
            //TODO 显示一堆按钮
            pbLoading.Visible = !flag;
            labelMsg.Text = tbAccount.Text + " 正在登录中...";
            labelMsg.Visible = !flag;
        }

        private void DelegateLogin(object sender, EventArgs e)
        {
            bool isKeyEvent = typeof(KeyEventArgs).IsAssignableFrom(e.GetType());
            if (!isKeyEvent || (((KeyEventArgs)e).KeyCode == Keys.Enter))
            {
                //修改界面为登录中...

                changeView(false);

                System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(delegate
                {
                    this.Invoke(new MethodInvoker(delegate
                    {
                       bool flag = postlogin();
                       if (flag) { this.Close(); }
                    }));

                }));
                thread.Start();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(LoginForm));
            if (!AppInfo.remenberPwd)
            {
                AppInfo.remenberPwd = true;
                pictureBox2.Image = global::EBQ.Properties.Resources.选中;
            }
            else
            {
                AppInfo.remenberPwd = false;
                pictureBox2.Image = global::EBQ.Properties.Resources.未选中;
            }
        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(LoginForm));
            if (!AppInfo.remenberPwd)
            {
                AppInfo.remenberPwd = true;
                pictureBox2.Image = global::EBQ.Properties.Resources.选中;
            }
            else
            {
                AppInfo.remenberPwd = false;
                pictureBox2.Image = global::EBQ.Properties.Resources.未选中;
            }


        }

        private void button2_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(@"http://per.ebaoquan.org/user/toForgetPassword");
        }


        private void button1_Click_1(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(@"https://account.ebaoquan.org/entUser/register");
        }
    }
}
